using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {


	private Collider2D box;
	private Animator anim;
	public bool inversion;

	public GameObject teleportDireita;
	public GameObject teleportEsquerda;

	public float speed;
	public float heightOfTheJump;
	public float cubeTime;
	public float animationTime;

	float touchStartPos;
	float startY;
	float startX;

	Touch touch;

	//public Vector3 positionMouse;
	public float X;
	public float Y;
	Vector3 dir;

	public KeyCode right;
	public KeyCode left;
	public KeyCode jumpButton;

	public bool onClick;

	public bool jump;
	public bool jumping;

	public static Player instance;

	public GUIStyle style;
	
	// Use this for initialization
	void Start ()
	{
		box =  gameObject.GetComponent<BoxCollider2D>();
		anim = gameObject.GetComponent<Animator>();

		instance = this;

	}
	
	// Update is called once per frame
	void Update ()
	{ 
		cubeTime -= Time.deltaTime;
		animationTime -= Time.deltaTime;
		if(animationTime < 0)
		{
			animationTime = 0;
		}
		if (cubeTime < 0)
		{
			cubeTime = 0;
		}
		if(Input.GetMouseButtonDown(0))
		{
			onClick = true;
		}
		else
		{
			onClick = false;
		}
		dir.x = Input.acceleration.x;
		dir.y = Input.acceleration.y;

		if(dir.sqrMagnitude > 1)
		{
			dir.Normalize ();
		}

				if(dir.x < -0.1 || Input.GetKey(left))
				{
					transform.Translate(-speed*Time.deltaTime,0,0);
					transform.localScale = new Vector3(-0.7f, 0.7f, 1f);
					anim.SetTrigger("Correndo");
					inversion = true;
				}
				 else if(dir.x > 0.1 || Input.GetKey(right))
				{
					transform.Translate(speed*Time.deltaTime,0,0);
					transform.localScale = new Vector3(0.7f, 0.7f, 1f);
					anim.SetTrigger("Correndo");
					inversion = false;
				}	
				else
				{
					anim.SetTrigger("Parada");
				}		

		if(Input.GetKey(jumpButton))
		{
			jump = true;

		}
			if(jump && !jumping)
			{
				transform.Translate(0, heightOfTheJump*Time.deltaTime,0);
				jumping = true;
				anim.SetTrigger("Pulando");

			}	
	}

	void OnCollisionEnter2D(Collision2D other) 
	{
		if(other.gameObject.tag == "teleport")
		{
			if(dir.x < -0.1 || Input.GetKey(left))
			{
				transform.position = new Vector3(teleportDireita.transform.position.x, startY,0);
			}
			else if(dir.x > 0.1 || Input.GetKey(right))
			{
				transform.position = new Vector3(teleportEsquerda.transform.position.x, startY,0);
			}
		}
		if(other.gameObject.tag == "chao")
		{
			startY = transform.position.y;
			startX = transform.position.x;
			jump = false;
			jumping = false;
		}
	}

	public void SaveGame(int SG)
	{
		float newSave = CurrentDeSave() + SG;

		PlayerPrefs.SetFloat("currentSave", newSave);
	}

	public float CurrentDeSave()
	{
		return PlayerPrefs.GetFloat("currentSave");
	}


	void OnGUI()
	{
		GUI.Label(new Rect(0,0, 200, 50), "currentSave = " + CurrentDeSave(), style );

	}

}
